{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import multiprocessing as mp\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def train_from_batch(d):\n",
    "    sleep(0.5)\n",
    "def load_data():\n",
    "    sleep(5)\n",
    "    return np.random.rand(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# def generator():\n",
    "#     q = mp.Queue(maxsize=2)\n",
    "#     ....\n",
    "#     for _ in range(n_files):\n",
    "#         current_data = q.get()\n",
    "#         for d in pre_processed(data):\n",
    "#             yield d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NCORE = 4\n",
    "\n",
    "def process(q, iolock):\n",
    "    from time import sleep\n",
    "    while True:\n",
    "        stuff = q.get()\n",
    "        if stuff is None:\n",
    "            break\n",
    "        with iolock:\n",
    "            print(\"processing\", stuff)\n",
    "        sleep(stuff)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "q = mp.Queue(maxsize=NCORE)\n",
    "iolock = mp.Lock()\n",
    "pool = mp.Pool(NCORE, initializer=process, initargs=(q, iolock))\n",
    "for stuff in range(20):\n",
    "    q.put(stuff)  # blocks until q below its max size\n",
    "    with iolock:\n",
    "        print(\"queued\", stuff)\n",
    "for _ in range(NCORE):  # tell workers we're done\n",
    "    q.put(None)\n",
    "pool.close()\n",
    "pool.join()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
